package com.frxuexi.document.view

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.document.DocEntity
import com.frxuexi.document.DocIntent
import com.frxuexi.document.DocViewModel
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.HttpType
import com.frxuexi.lib_base.R
import com.frxuexi.lib_base.RoutePath
import com.frxuexi.lib_base.UiState
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@Composable
fun DocPage(navHostController: NavHostController, vm: DocViewModel = hiltViewModel()) {
    var list = remember {
        SnapshotStateList<DocEntity>()
    }
    val state = rememberUltraSwipeRefreshState()

    var page by remember {
        mutableStateOf(1)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        if(it.type==HttpType.DELETE){
                            ToastUtils.showLong("删除成功")
                            list.clear()
                            vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", 1))))
                        }else{
                            Log.i("===", it.data.toString())
                            list.addAll(it.data as Collection<DocEntity>)
                        }
                    }

                    else -> {}
                }
            }
        }
        vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", 1))))
    })

    LaunchedEffect(key1 = state.isRefreshing, block = {
        if(state.isRefreshing){
           /* if(page!=1){
                list.clear()
            }*/
            page=1
            vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", 1))))
            state.isRefreshing=false
        }
    })

    LaunchedEffect(key1 = state.isLoading, block = {
        if(state.isLoading){
            page++
            vm.sendIntent(DocIntent.getDoc(mapOf(Pair("userId", 1), Pair("page", page))))
            state.isLoading=false
        }
    })


    Scaffold(floatingActionButton = {
        Image(painter = painterResource(id = R.drawable.icon159), contentDescription = "",
            Modifier.clickable {
                navHostController.navigate(RoutePath.LOCAL)
            })
    }) {
        Column(Modifier.padding(it)) {
            BaseTitle(title = "文件", navHostController)
            UltraSwipeRefresh(state = state, onRefresh = { state.isRefreshing=true }, onLoadMore = { state.isLoading=true }) {
                LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp)){
                    items(list){
                        DocItem(entity = it){
                            vm.sendIntent(DocIntent.delete(mapOf("FileId" to it.fileId)))
//                            list-=it
                        }
                    }
                }
            }
        }
    }

}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DocItem(entity: DocEntity,deleteClick: () -> Unit){
    var mod = Modifier
        .size(60.dp)
        .clip(RoundedCornerShape(20.dp))
    Row(Modifier.padding(horizontal = 20.dp)
        .combinedClickable(onClick = {
        ToastUtils.showLong(entity.fileName+"点击了")
    }, onDoubleClick = {
            ToastUtils.showLong(entity.fileName+"双击了")
        }, onLongClick = {
            deleteClick()

        })) {
        val end=entity.fileName.split(".")[1]
        if(arrayOf("png","jpg","jpeg","webp").contains(end)) {
            AsyncImage(
                model = entity.filePath, contentDescription = "",
                modifier =mod
            )
        }else{
            Image(painter = painterResource(id = R.drawable.icon3), contentDescription = "",
                modifier = mod)
        }
        Spacer(modifier = Modifier.width(10.dp))
        Column(Modifier.height(60.dp), verticalArrangement = Arrangement.SpaceAround) {
            Text(text = entity.fileName, maxLines = 1, overflow = TextOverflow.Ellipsis)
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.fileTime)
            Text(text = time , fontSize = 14.sp, color = Color.Gray)
        }
    }
}